package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/12/19 22:52
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService
{
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;      // 用于生成静态页面的数据
    @Value("${out_put_path}")
    private String outPutPath;

    //新增套餐信息，同时需要关联检查组
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds)
    {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckgroup(setmealId, checkgroupIds);
        //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        // 每次添加套餐时, 重新生成新的静态页面
        generateMobileStaticHtml();
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean)
    {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //设置套餐和检查组多对多关系，操作t_setmeal_checkgroup
    public void setSetmealAndCheckgroup(Integer setmealId, Integer[] checkgroupIds)
    {
        if (checkgroupIds != null && checkgroupIds.length > 0)
        {
            for (Integer checkgroupId : checkgroupIds)
            {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    @Override
    public List<Setmeal> findAll()
    {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id)
    {
        return setmealDao.findById(id);
    }

    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap)
    {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try
        {
            // 加载模板文件
            Template template = configuration.getTemplate(templateName);
            // 生成文件输出流
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPutPath + "/" + htmlPageName)));
            // 生成 .html文件
            template.process(dataMap, out);
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {     // 关闭流
            try
            {
                if (null != out)
                {
                    out.flush();
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    // 生成静态页面  套餐列表 + 套餐详情
    public void generateMobileStaticHtml()
    {
        // 查询所有的 Setmeal对象
        List<Setmeal> setmealList = this.findAll();
        // 生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        // 生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList)
    {
        Map<String, Object> dataMap = null;
        for (Setmeal setmeal : setmealList)
        {
            dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));     // 获取完全的套餐  检查组 + 检查项
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" +
                    setmeal.getId() + ".html", dataMap);

        }
    }

    private void generateMobileSetmealListHtml(List<Setmeal> setmealList)
    {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //为模板提供数据
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount()
    {
        return setmealDao.findSetmealCount();
    }
}
